package com.example.lenovo.asia5b.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;


/**
 * 上传头像
 * Created by lenovo on 2017/7/8.
 */

public class UploadHeadPortraitActivity extends BaseActivity implements ICallBack {

    private LoadingDalog loadingDalog;
    private String photoFile;//头像地址
    private String user_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_head_portrait);
        Intent intent = getIntent();
        user_id = intent.getStringExtra("user_id");
        initView();
    }

    private void initView(){
        loadingDalog = new LoadingDalog(this);
        F.id(R.id.activity_upload_head_portrait_next).clicked(this);//下一步
        F.id(R.id.activity_upload_head_image_head).clicked(this);//头像
        F.id(R.id.btn_complete).clicked(this);//完成
        Intent intent = new Intent(this,WriteUserDataActivity.class);
        if (getIntent().hasExtra("register")) {
            intent.putExtra("register",getIntent().getStringExtra("register"));
            intent.putExtra("phone",getIntent().getStringExtra("phone"));
        }
        intent.putExtra("user_id",user_id);
        startActivity(intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.activity_upload_head_portrait_next://下一步
                intent = new Intent(this,WriteUserDataActivity.class);
                if (getIntent().hasExtra("register")) {
                    intent.putExtra("register",getIntent().getStringExtra("register"));
                    intent.putExtra("phone",getIntent().getStringExtra("phone"));
                }
                intent.putExtra("user_id",user_id);
                startActivity(intent);
                break;
            case R.id.activity_upload_head_image_head://头像
                loadingDalog.showPhoto();
                break;
            case R.id.btn_complete:
                if (F.id(R.id.btn_complete).getButton().getTag()==null){
                    return;
                }
                String url = F.id(R.id.btn_complete).getButton().getTag().toString();
                if (!TextUtils.isEmpty(url)) {
                    refresh(url);
                }
                break;
        }
    }
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int)json.getInt("State");
                        if(state == 0) {
                            String url = (String)json.getString("url");
                            U.Toast(UploadHeadPortraitActivity.this,getResources().getString(R.string.cg));
                            Intent intent = new Intent(UploadHeadPortraitActivity.this,WriteUserDataActivity.class);
                            if (getIntent().hasExtra("register")) {
                                intent.putExtra("register",getIntent().getStringExtra("register"));
                                intent.putExtra("phone",getIntent().getStringExtra("phone"));
                            }
                            intent.putExtra("url",url);
                            intent.putExtra("user_id",user_id);
                            startActivity(intent);
                        }
                        else if(state == 1){
                            U.Toast(UploadHeadPortraitActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(UploadHeadPortraitActivity.this,getResources().getString(R.string.cscw));
                        }
                    }catch (Exception e) {

                    }

                } else {
//                U.Toast(MyDataActivity.this, "数据为空");
                }
                loadingDalog.dismiss();
            }
        }
    };



    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    Uri cameraUri = null;

    @Override
    protected void onActivityResult(int requestCode, int arg1, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, arg1, data);
        switch (requestCode) {
            case 101:// 相机
//                listPicture.clear();
                if (data != null) {
                    if (data.getExtras() != null) {
                        cameraUri = loadingDalog.getPhotoUrihotoUri();
                        hear(null);
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                } else {
                    if (loadingDalog.getPhotoUrihotoUri() != null) {
                        cameraUri = loadingDalog.getPhotoUrihotoUri();
                        hear(null);
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                }
                // setPicture();
                break;
            case 102:// 相册返回
//                listPicture.clear();
                cameraUri = null;
                if (data != null) {
                    if (data.getData() != null) {
                        cameraUri = data.getData();
                        hear(null);
                    } else {
                        U.Toast(this, getResources().getString(R.string.system_no_getpic));
                    }
                }else if (loadingDalog.getPhotoUrihotoUri() != null) {
                    cameraUri = loadingDalog.getPhotoUrihotoUri();
                    hear(null);
                } else {
                    U.Toast(this, getResources().getString(R.string.system_no_getpic));
                }
                break;
            case 103:
                break;
        }

    }

    public void hear(Intent data) {
        Bitmap photo = null;
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                photo = bundle.getParcelable("data");
            } else if (data != null) {
                Uri uri1 = data.getData();
                try {
                    photo = MediaStore.Images.Media.getBitmap(getContentResolver(), uri1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }  else {
            try {
                photo = MediaStore.Images.Media.getBitmap(getContentResolver(), cameraUri);
                //图片太大实现压缩功能
                if (DownloadPicture.getBitmapSize(photo) > 1000800) {
                    photo = DownloadPicture.smallOneFifth(photo);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (photo == null) {
            return;
        }
        BufferedOutputStream bos = null;
        if (photo != null) {
            File dirFile = new File(Setting.IMAGE_ROOTPATH);
            if (!dirFile.exists())
                dirFile.mkdirs();
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyyMMddhhmmss", Locale.ENGLISH);
            File uploadFile = new File(dirFile + "/"
                    + sDateFormat.format(new java.util.Date())
                    + ".jpg");

            char[] chars = "0123456789abcdef".toCharArray();
            StringBuilder sb = new StringBuilder("");
            int bit;
            try {
                uploadFile.createNewFile();
                bos = new BufferedOutputStream(new FileOutputStream(uploadFile));
                photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                FileInputStream fis = new FileInputStream(uploadFile);
                byte[] b = new byte[fis.available()];
                fis.read(b);
                for (int i = 0; i < b.length; i++) {
                    bit = (b[i] & 0x0f0) >> 4;
                    sb.append(chars[bit]);
                    bit = b[i] & 0x0f;
                    sb.append(chars[bit]);
                }

                fis.close();
//                                String binary = new BigInteger(1, b).toString(16);
                photoFile = uploadFile.getAbsolutePath();
                F.id(R.id.btn_complete).getButton().setTag(sb.toString());
                DownloadPicture.loadThisLocality(photoFile,F.id(R.id.activity_upload_head_image_head).getImageView());
            } catch (IOException e) {
                U.Toast(UploadHeadPortraitActivity.this, e.getLocalizedMessage());
            } finally {
                if (bos != null) {
                    try {
                        bos.flush();
                        bos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }


    /**
     * 上传头像
     * @param binary
     */
    public void refresh(String binary) {
        loadingDalog.show();
        try {
            Map<String, String> formMap = new HashMap<String, String>();
            String url = Setting.UPLODE_IMAGE;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id" + user_id, "time" + time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            formMap.put("user_id", user_id);
            formMap.put("time", time);
            formMap.put("sign",md5_32);
            Map<String, String> formMap2 = new HashMap<String, String>();
            formMap2.put("photo", binary);
            JsonTools2.dataHttps(this, url, formMap,formMap2, 0);
        }catch (Exception e) {
        }
    }
}
